'''
Entry point for the GMZ application/library.

This file may be called or loaded as a module.
'''

import os
import sys
import arcmgmt
import gmail

import config

def zipandsend(toarcpath, description, additionalInfo=""):
    '''Takes the given path, generates .zip archvie(s), and emails them.
    The description is put in the subject line of every email.'''
    
    #Basic processing and checks of the path
    toarcpath = os.path.abspath(toarcpath)
    assert os.path.exists(toarcpath)
    
    ##It is assumed the directory does not end with '\'
    ##Just to be safe - probably not necessary
    ##directory = directory.rstrip("\\")
    
    #The primary backup
    bk = None
    
    try:
        #Create the backup
        #This will sort the files into archives of appropriate sizes
        #It will also zip them
        bk = arcmgmt.Backup(toarcpath)
        
        #Number of archives (.zip files) in the backup
        numPieces = len(bk)
        
        #Update status to user
        print ""
        print "Sending Mail ({0} archives totaling {1} MB)".format(
            numPieces, 
            bk.get_comp_size()/1000000.0)
        
        #Iterate pieces, generate subject and body text, then send email
        i = 0
        for piece in bk:
            i += 1
            
            #Email subject
            subject = "[GMZ][{0}][{1}][{2}] {3} of {4}: {5} - Backup of \'{6}\'".format(
                    bk.get_name(), #0
                    bk.get_backuptimestamp(True, asStringDate=True, asStringTime=False), #1
                    bk.get_backuptimestamp(True, asStringDate=False, asStringTime=True), #2
                    i, numPieces, #3, 4
                    description, #5
                    toarcpath) #6
            
            #Email body
            body = ""
            if numPieces > 1:
                #Be explicit that backup files may exist elsewhere
                #ie there might be other emails associated with the backup
                body += "There are {0} other archives in this backup.\r\n" \
                    .format(numPieces - 1)
                body += "To find related archives, search for: \"{0}\"\r\n\r\n" \
                        .format(bk.get_searchkey())
            
            if not additionalInfo is None and len(additionalInfo) > 0:
                body += "Additional Info:\r\n"
                body += str(additionalInfo)
                body += "\r\n"
            
            body += "File(s) listed below are relative to: \'{0}\\\'\r\n".format(bk._srcDir)
            body += "File(s) in archive \'{0}.zip\':\r\n".format(piece.get_piece_name())
            
            for filePath in piece:
                body += "\t" + filePath.replace(bk._srcDir + "\\", "", 1) + "\r\n"
            
            #Give some udate before sending mail
            arcSize = piece.get_comp_size()/1000000.0
            print "  Sending Archive {0}/{1} ({2} MB)".format(i, len(bk), arcSize)
            
            #Send it to google to keep for eternity (well hopefully)
            gmail.send_mail(subject, body, piece.archive_path())

    finally:
        if not bk is None:
            #Remove all of the local archives
            bk.delete_pieces()
    
    print ""
    print "Done"

if __name__ == "__main__":
    
    #GMZ has been called as a stand alone application
    
    try:
        #Other versions might work - they just have not been tested. This is easiest
        assert sys.version_info[0] == 2, "Only python 2.6 is supported"
        assert sys.version_info[1] == 6, "Only python 2.6 is supported"
        
        #Currently, only the backup of one directory is supported
        #extract the directory from the argument passed to this script
        assert len(sys.argv) == 2, "Only backup of a single file or directory is currently supported"
        toBk = sys.argv[1]
        assert os.path.exists(toBk), "Path does not exist: " + toBk
        
        #Check configuration
        #TODO: Support configuration
        assert config.is_configured(), "GMZ has not been configured"
        
        #Echo the directory being backed up to the user
        if os.path.isdir(toBk):
            print "Backing up directory \"{0}\"".format(toBk)
        else:
            assert os.path.isfile(toBk) #Hopefully redundant
            print "Backing up file \"{0}\"".format(toBk)
        
        print ""
        
        #Enter a description which will be put in the subject of emails sent
        #which relate to this backup
        description = raw_input("Description (part of email subject): ")
        
        #Remove leading and trailing whitespace - makes it look nicer
        description = description.strip()
        
        if len(description) == 0:
            #The user has not entered a subject
            description = "GMZ Quick Backup"
        
        #Do the backup
        zipandsend(toBk, description)

    except Exception as err:
        print ""
        print "ERROR: " + str(err)
        raise
    finally:
        print ""
        raw_input("Press enter to coninue...")